n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))


class UnionFind:
    def __init__(self, n_size):
        self.fa = list(range(n_size + 1))
        self.size = [1] * (n_size + 1)

    def find(self, x):
        if self.fa[x] != x:
            self.fa[x] = self.find(self.fa[x])
        return self.fa[x]

    def union(self, x, y):
        root_x = self.find(x)
        root_y = self.find(y)
        if root_x == root_y:
            return False
        self.fa[root_y] = root_x
        self.size[root_x] += self.size[root_y]
        return True


max_size = max(max(a), max(b))
uf = UnionFind(max_size)
for va in a:
    uf.union(va, a[0])
